const Category = require('@models/category');
const { Op } = require('sequelize');

class CategoryService {
  /**
   * 获取分类列表
   */
  async getCategories({ page, pageSize, name, status }) {
    // 确保分页参数是有效的数字
    const pageNum = Math.max(1, parseInt(page) || 1);
    const pageSizeNum = Math.max(1, parseInt(pageSize) || 10);
    
    const where = {};
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`
      };
    }
    
    // 只有当 status 是有效的数字时才添加到查询条件
    if (status !== undefined && status !== '' && !isNaN(parseInt(status))) {
      where.status = parseInt(status);
    }

    console.log('查询条件:', where);
    console.log('分页参数:', { pageNum, pageSizeNum });

    const { count, rows } = await Category.findAndCountAll({
      where,
      offset: (pageNum - 1) * pageSizeNum,
      limit: pageSizeNum,
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });

    return {
      list: rows,
      total: count
    };
  }

  /**
   * 获取所有启用的分类
   */
  async getAllEnabledCategories() {
    const categories = await Category.findAll({
      where: { status: 1 },
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });

    return {
      list: categories,
      total: categories.length
    };
  }

  /**
   * 获取分类树形结构
   */
  async getCategoryTree() {
    const categories = await Category.findAll({
      where: { status: 1 },
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });

    const buildTree = (parentId = 0) => {
      const children = categories.filter(item => item.parent_id === parentId);
      return children.map(item => ({
        ...item.toJSON(),
        children: buildTree(item.id)
      }));
    };

    const tree = buildTree();
    return {
      list: tree,
      total: categories.length
    };
  }

  /**
   * 获取分类详情
   */
  async getCategoryById(id) {
    return await Category.findByPk(id);
  }

  /**
   * 创建分类
   */
  async createCategory(data) {
    return await Category.create(data);
  }

  /**
   * 更新分类
   */
  async updateCategory(id, data) {
    const category = await Category.findByPk(id);
    if (!category) {
      return null;
    }
    return await category.update(data);
  }

  /**
   * 删除分类
   */
  async deleteCategory(id) {
    const category = await Category.findByPk(id);
    if (!category) {
      return false;
    }

    // 检查是否有子分类
    const hasChildren = await Category.count({ where: { parent_id: id } });
    if (hasChildren > 0) {
      throw new Error('该分类下有子分类，无法删除');
    }

    // 检查是否有关联的商品
    const hasProducts = await category.countProducts();
    if (hasProducts > 0) {
      throw new Error('该分类下有商品，无法删除');
    }

    await category.destroy();
    return true;
  }

  /**
   * 更新分类状态
   */
  async updateCategoryStatus(id, status) {
    const category = await Category.findByPk(id);
    if (!category) {
      return null;
    }
    return await category.update({ status });
  }

  /**
   * 更新分类排序
   */
  async updateCategorySort(id, sort) {
    const category = await Category.findByPk(id);
    if (!category) {
      return null;
    }
    return await category.update({ sort });
  }
}

module.exports = new CategoryService(); 